package io.github.betacatcode.executor;

import io.github.betacatcode.model.Account;
import io.github.betacatcode.model.Money;
import io.github.betacatcode.repository.AccountRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@AllArgsConstructor
public class AccountExecutor {
    private final AccountRepository accountRepository;

    /**
     * 转账
     *
     * @param sourceAccountNumber 转出账户号
     * @param targetAccountNumber 转入账户号
     * @param money               金额
     * @throws Exception 异常
     */
    @Transactional(rollbackFor = Exception.class)
    public void transfer(String sourceAccountNumber, String targetAccountNumber, Money money) throws Exception {
        //校验金额
        money.verify();

        //获取账户
        Account source = accountRepository.getAccountByAccountNumber(sourceAccountNumber);
        Account target = accountRepository.getAccountByAccountNumber(targetAccountNumber);

        //转出以及转入
        source.deposit(money.getAmount());
        target.withdraw(money.getAmount());

        accountRepository.save(source);
        accountRepository.save(target);
    }
}
